package com.veo.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.veo.entity.Cart;
import com.veo.entity.CartVo;
import com.veo.entity.UserCartVo;
import com.veo.mapper.CartMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.util.List;

@Service
public class CartService extends ServiceImpl<CartMapper, Cart> {

    @Autowired
    private CartMapper cartMapper;

    /**
     * 根据用户id查询用户的购物车记录
     * @param userId
     * @return
     */
    public List<CartVo> findCartVoById(Integer userId){
        return cartMapper.findCartListByUserId(userId);
    }

    /**
     * 根据商品id查询购物车
     */
    public List<CartVo> findCartVoByIds(String ids){
        return cartMapper.findCartVoByIds(Arrays.asList(ids.split(",")));
    }


    /**
     * 统计用户购物车的总计
     */
    public double getCartItemTotal(List<CartVo> list){
        double sum = 0.0;
        for (CartVo cartVo : list) {
            sum += cartVo.getCount() * cartVo.getNewPrice();
        }
        return sum;
    }

    //批量删除
    public String batchDelete(String ids) {
        if (ids != null){
            String[] idArray = ids.split(",");
            cartMapper.deleteBatchIds(Arrays.asList(idArray));
        }
        return "success";
    }

    //包装用户购物车信息
    public UserCartVo wrapCart(List<CartVo> cartVoList){
        UserCartVo userCartVo = new UserCartVo();
        //获取商品的总条数和总的价格
        userCartVo.setCount(cartVoList.size());
        userCartVo.setTotalPrice(getCartItemTotal(cartVoList));
        return userCartVo;
    }
}
